package service

import (
	"ia/apps/admin/web/dts/sin"
	"ia/apps/admin/web/dts/sout"
	"ia/apps/admin/web/repository"
	"ia/common/model/modeladmin"
	"ia/common/storage"
	"ia/common/support"
	"ia/common/support/define"

	"github.com/kataras/golog"
	"github.com/kataras/iris/v12"
)

type AdminLogService interface {
	Delete(ctx iris.Context)
	Table(ctx iris.Context)
}

func NewAdminLogService() *adminLogService {
	return &adminLogService{}
}

type adminLogService struct{}

func (impl *adminLogService) Delete(ctx iris.Context) {
	var (
		code   define.Code
		err    error
		idList = make([]int, 0)
	)
	if err = ctx.ReadJSON(&idList); err != nil {
		goto ERR
	}

	if err = storage.GDB1.Delete(&modeladmin.AdminLog{}, "id in ?", idList).Error; err != nil {
		goto ERR
	}
	support.Ok_(ctx)
	return
ERR:
	golog.Errorf("错误：%s", err)
	support.InternalServerError(ctx, code)
}

func (impl *adminLogService) Table(ctx iris.Context) {
	var (
		code   define.Code
		err    error
		in     sin.LogIn
		total  int64
		result = make([]*sout.AdminLogOut, 0)
		db     = storage.GDB1.Model(&modeladmin.AdminLog{})

		userList   = make([]*sout.AdminUserOut, 0)
		policyList = make([]*modeladmin.AdminPolicy, 0)
	)
	if err = ctx.ReadQuery(&in); err != nil {
		goto ERR
	}
	if in.UserId > 0 {
		db.Where("creator_id=?", in.UserId)
	}
	if in.GroupName != "" {
		db.Where("group_name=?", in.GroupName)
	}
	if in.Name != "" {
		db.Where("name=?", in.Name)
	}
	if err = db.Count(&total).Error; err != nil {
		goto ERR
	}
	if err = db.Preload("Creator").
		Offset(in.Offset()).Limit(in.PageSize).
		Order("created_time desc").
		Find(&result).Error; err != nil {
		goto ERR
	}

	if err = repository.NewCurd().OmitDefault().List(&userList); err != nil {
		goto ERR
	}
	if err = repository.NewCurd().List(&policyList); err != nil {
		goto ERR
	}
	support.VxeTableData(ctx, in.PageSize, in.CurrentPage, total, result, iris.Map{
		"userList":   userList,
		"policyList": policyList,
	})
	return
ERR:
	golog.Errorf("错误：%s", err)
	support.InternalServerError(ctx, code)
}
